import actionTypes from './actionTypes';
import { getUserInfo } from '../requests';
export const loginSuccess = userInfo => ({
  type: actionTypes.LOGIN_SUCCESS,
  payLoad: userInfo
});
export const loginFailed = () => {
  window.localStorage.removeItem('authToken');
  window.localStorage.removeItem('userStorageInfo');
  window.sessionStorage.removeItem('authToken');
  window.sessionStorage.removeItem('userStorageInfo');
  return {
    type: actionTypes.LOGIN_FAILED
  };
};
export const startLogin = () => ({
  type: actionTypes.START_LOGIN
});
export const logout = () => dispatch => {
  dispatch(loginFailed());
};
export const login = userInfo => dispatch => {
  dispatch(startLogin());
  getUserInfo(userInfo)
    .then(res => {
      if (res.data.code === 200) {
        let { authToken, ...userStorageInfo } = res.data.data;
        dispatch(loginSuccess(res.data.data));
        //判断是否选择记住我
        if (userInfo.remember) {
          window.localStorage.setItem('authToken', authToken);
          window.localStorage.setItem(
            'userStorageInfo',
            JSON.stringify(userStorageInfo)
          );
        } else {
          window.sessionStorage.setItem('authToken', authToken);
          window.sessionStorage.setItem(
            'userStorageInfo',
            JSON.stringify(userStorageInfo)
          );
        }
      } else dispatch(loginFailed());
    })
    .catch(() => {
      dispatch(loginFailed());
    });
};

export const changeAvatar = avatarUrl => ({
  type: actionTypes.CHANGE_AVATAR,
  payLoad: {
    avatar: avatarUrl
  }
});
